﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace SmlEngine.UI.Input
{
    public sealed class InputState
    {
        public KeyboardState KeyboardState { get; private set; }
        public MouseState MouseState { get; private set; }
        public Dictionary<PlayerIndex, GamePadState> GamePadStates { get; private set; }

        public InputState(KeyboardState? keyboard, MouseState? mouse, Dictionary<PlayerIndex, GamePadState> gamePad)
        {
            if (keyboard.HasValue)
                KeyboardState = keyboard.Value;
            else
                KeyboardState = Keyboard.GetState();

            if (mouse.HasValue)
                MouseState = mouse.Value;
            else
                MouseState = Mouse.GetState();

            if (gamePad != null)
            {
                GamePadStates = gamePad;
            }
            else
            {
                GamePadStates = new Dictionary<PlayerIndex, GamePadState>(PlayerIndexEqualityComparer.Default);
                GamePadStates[PlayerIndex.One] = GamePad.GetState(PlayerIndex.One);
                GamePadStates[PlayerIndex.Two] = GamePad.GetState(PlayerIndex.Two);
                GamePadStates[PlayerIndex.Three] = GamePad.GetState(PlayerIndex.Three);
                GamePadStates[PlayerIndex.Four] = GamePad.GetState(PlayerIndex.Four);
            }
        }

        public bool IsKeyMapDown(KeyMap keyMap)
        {
            return KeyboardState.IsKeyDown(keyMap.Key) ||
                   GamePadStates[InputSettings.ControllingPlayer].IsButtonDown(keyMap.Button);
        }

        public bool IsKeyMapUp(KeyMap keyMap)
        {
            return KeyboardState.IsKeyUp(keyMap.Key) &&
                   GamePadStates[InputSettings.ControllingPlayer].IsButtonUp(keyMap.Button);
        }
    }
}
